# -- coding: utf-8 --
# @time : 2023/6/8
# @author : 周梦泽
# @file : task_run.py
# @software: pycharm
# 任务执行模块
import importlib
import json
import time
import traceback

import backoff

from autoTask.operaitonAid.taobao.correlation_analysis_module.relatedAnalysis import RelatedAnalysis
from autoTask.operaitonAid.taobao.get_store_info_module.get_store_info import StoreInfo
from autoTask.operaitonAid.taobao.search_ranking_module.searchRank import SearchRank
from autoTask.operaitonAid.taobao.through_train_module.add_keywords_price import AddCommodity
from autoTask.operaitonAid.taobao.title_maker_module.title_creator import ParseExcelToTitle
from autoTask.operaitonAid.taobao.traffics_source_module.traffics_source import ProductSingleAnalysis
from autoTask.operaitonAid.utils.pc_capture import screenshot_captured
from autoTask.operaitonAid.utils.request_data import requests_data
from autoTask.operaitonAid.utils.update_machine_status import update_status_pc
from common.logger.log import log_
from common.utils.end_thread import async_raise
from request.utils.request import Request


@update_status_pc
def operaiton_add_title_and_add_keywords(params: dict):
    """
    商品修改标题并添加关键词/现已分离为两个任务
    :param params:任务参数
    :return:
    """

    if params.get("addNewTitle"):
        ParseExcelToTitle()(params)
    if params.get("addKeyWord"):
        AddCommodity(params).add_keywords()


@update_status_pc
def operaiton_add_title(params: dict):
    """
    商品修改标题
    :param params:任务参数
    :return:
    """
    ParseExcelToTitle()(params)


@update_status_pc
def ztc_add_keywords(params: dict):
    """
    直通车添加关键词
    :param params:任务参数
    :return:
    """

    AddCommodity(params).add_keywords()


@backoff.on_exception(backoff.constant, Exception, max_tries=3, interval=5,
                      on_backoff=lambda details: log_.error(traceback.format_exc()))
def operaiton_get_keywords():
    """
    获取关键词将数据发送到Java中台，由中台存储到数据库中
    :return:
    """
    search_obj_list = [
        {
            "account": "中山杰特电器:星星",
            "password": "yzt123456",
            "searchContent": r"平底锅",
            "dateCycle": 7,
            "dataWord": "搜索词"
        },
    ]
    for params in search_obj_list:
        datalist = SearchRank(params)()
        keywords = datalist["关键词"].tolist()
        keywords_obj = RelatedAnalysis(params, keywords)()
        category = params["searchContent"]
        Request("post", uri="public/operationAid/KeyWord/add", params={
            "categoryName": category,
            "dataList": keywords_obj
        }, req_title="运营助手-获取市场关键词", req_is_log=True).send()


@update_status_pc
def store_info_task(params: dict):
    """
    获取店铺信息任务/现已改为统一接口
    :return:
    """

    store_info = StoreInfo(params)()
    # 这里写将store_info_json到java中台接口发送
    log_.info(f"{store_info}")
    requests_data("post", uri="public/store/tb/commit", params=store_info,
                  req_title="运营助手-获取店铺信息",
                  req_is_log=True, req_param_is_log=False)


def get_screen_shot(result_queue):
    """
    从队列中获取截图
    :param result_queue:截图队列
    :return:
    """
    screen_shot = screenshot_captured()
    result_queue.put(screen_shot)


def delay_exit_app(delay: int = 3, thread_id=None):
    """
    延迟退出
    :param thread_id: 线程ID
    :param delay:延迟多少秒退出应用
    :return:
    """
    if thread_id:
        # 如果有任务先stop任务
        async_raise(thread_id, SystemExit)
    time.sleep(delay)
    service = importlib.import_module('service')
    # 解决循环导包问题，结束flask服务
    service.shutdown()
    exit()


def product_single_task(params: dict):
    """
    流量来源/商品单品分析
    :param params:任务参数
    :return:
    """
    df_json, store_name = ProductSingleAnalysis(params)()
    merged_data = {}
    # 配合对接，改变Json结构
    # 遍历原始数据，将同类项合并，并添加store_name字段
    for d in json.loads(df_json):
        print(d)
        key = (d['商品标题'], d['商品id'], d['日期'])
        if key not in merged_data:
            merged_data[key] = {
                'productTitle': d['商品标题'],
                'productId': d['商品id'],
                'dataCycle': d['日期'],
                'storeName': store_name,
                'exponentialFieldListJson': []
            }
        merged_data[key]['exponentialFieldListJson'].append({
            'trafficsSource': d['流量来源'],
            'visitorNum': d['访客人数'],
            'buyersNum': d['下单买家数'],
            'orderCvsRate': d['下单转化率'],
            'pageView': d['浏览量'],
            'percentageOfPageViews': d['浏览量(占比)'],
            'inStoreJump': d['店内跳转人数'],
            'outStoreJump': d['跳出本店人数'],
            'collectorNum': d['收藏人数'],
            'collectionRate': d['收藏率'],
            'additionalPurchase': d['加购人数'],
            'additionRate': d['加购率'],
            'payoutsNum': d['支付件数'],
            'paidBuyersNum': d['支付人数'],
            'amountPaid': d['支付金额'],
            'payCvsRate': d['支付转化率'],
            'directPayBuyersNum': d['直接支付买家数'],
            'payAfterCollectionBuyersNum': d['收藏商品-支付买家数'],
            'payAfterAttentionBuyersNum': d['粉丝支付买家数'],
            'buyMoreBuyersNum': d['加购商品-支付买家数'],
            'perCustomer': d['客单价'],
            'uvValue': d['uv价值']
        })
    data_list = list(merged_data.values())
    for data in data_list:
        time.sleep(1)
        data['exponentialFieldListJson'] = json.dumps(data['exponentialFieldListJson'], ensure_ascii=False)
        requests_data("post", uri="product/trafficSource/robot/public/CommitData", params=data,
                      req_title="运营助手-获取店铺信息",
                      req_is_log=True, req_param_is_log=False)
    # print(json.dumps(merged_data, ensure_ascii=False))


if __name__ == '__main__':
    param = {
        "account": "中山杰特电器:星星",
        "password": "yzt123456",
        "sourceOfTraffic": "最后一次访问来源",  # 每一次访问来源/第一次访问来源/最后一次访问来源/
        "dataCycle": 30
    }
    product_single_task(param)
